import { Button, Card, Input, Form, InputNumber, Radio, Select, Modal, Cascader, Spin, Row, Col } from 'antd';
import { connect } from 'umi';
import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import Contanst from '@/config/contanst';
import { Map, Marker } from 'react-amap';
import Autocomplete from '@/components/AMapAutoComplete';
import db from '@/utils/localstorage';

const FormItem = Form.Item;

const Loading = <div className="example"><Spin /></div>
/**
 * 默认地图中心点位置
 */
const defaultPosition = {
  longitude: 118.805871,
  latitude: 32.0835
}
const BasicForm = props => {
  const { submitting } = props;
  const [form] = Form.useForm();
  const [visible, setVisible] = React.useState(false);
  const [tAddress, setTAddress] = React.useState('');
  const [modalPosition, setModalPosition] = React.useState({ longitude: '', latitude: '' });
  const [tPosition, setTPosition] = React.useState({ longitude: defaultPosition.longitude, latitude: defaultPosition.latitude });


  /**
   * 地图标记事件
   */
  const markerEvents = {
    dragend: (e) => {
      setTPosition({
        longitude: e.lnglat.lng,
        latitude: e.lnglat.lat
      })
    }
  }

  /**
   * 调整位置后表单地图标记体现
   */
  const positionProps = {
    longitude: modalPosition.longitude || defaultPosition.longitude,
    latitude: modalPosition.latitude || defaultPosition.latitude
  }
  const pluginProps = {

  }
  const formItemLayout = {
    labelCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 7,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 12,
      },
      md: {
        span: 10,
      },
    },
  };
  const submitFormLayout = {
    wrapperCol: {
      xs: {
        span: 24,
        offset: 0,
      },
      sm: {
        span: 10,
        offset: 7,
      },
    },
  };

  const onFinish = async() => {
    const values = await form.validateFields();
    const { dispatch } = props;
    if (values.addressArr) {
      values.provincial = values.addressArr[0]
      values.city = values.addressArr[1]
      values.district = values.addressArr[2]
      delete values.addressArr
    }
    values.longitude = modalPosition.longitude || ""
    values.dimensions = modalPosition.latitude || ""
    dispatch({
      type: 'cubeShop/add',
      payload: values,
    });
  };

  /**
   * 调整位置
   */
  const changePosition = () => {
    setModalPosition({
      longitude: tPosition.longitude || defaultPosition.longitude,
      latitude: tPosition.latitude || defaultPosition.latitude
    })
    setVisible(true)
  }

  /**
   * 输入框选择位置
   */
  const selectfunc = (e) => {
    if (e.poi.location) {
      setTPosition({
        longitude: e.poi.location.lng,
        latitude: e.poi.location.lat
      })
      setTAddress(e.poi.address);
    }
  }

  /**
   * 确认调整位置
   */
  const handleOk = () => {
    setModalPosition({
      longitude: tPosition.longitude,
      latitude: tPosition.latitude
    })
    form.setFieldsValue({
      address:tAddress
    })
    setVisible(false)
  }

  /**
   * 取消调整位置
   */
  const handleCancel = () => {
    setVisible(false)
  }

  return (
    <PageHeaderWrapper>
      <Card bordered={false}>
        <Form
          style={{
            marginTop: 8,
          }}
          form={form}
          name="basic"
        >
           <FormItem
            {...formItemLayout}
            label="场馆名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入场馆名称',
              },
            ]}
          >
            <Input placeholder="请输入"/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="电话"
            name="telephone"
            rules={[
              {
                required: true,
                message: '请输入电话号码',
              },
            ]}
          >
            <Input placeholder="请输入" />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="地址"
            name="addressArr"
            rules={[
              {
                required: true,
                message: '请选择地址',
              },
            ]}
          >
            <Cascader placeholder="请选择" fieldNames={{ label: 'name', value: 'id', children: 'children' }} options={db.get('areaList') || []} />
          </FormItem>
          <FormItem
            {...formItemLayout}
            wrapperCol={{ span: 10, offset: 7, }}
            name="address"
          >
            <Input placeholder="请输入场馆地址" addonAfter={<a type="primary" onClick={changePosition}>调整定位</a>} />
          </FormItem>
          <FormItem
            {...formItemLayout}
            wrapperCol={{ span: 10, offset: 7, }}
            name="address"
          >
            <div style={{ height: 200 }}>
              <Map amapkey={Contanst.AMapKey} zoom={15} loading={Loading} center={positionProps} plugins={['ToolBar']}>
                <Marker position={positionProps} />
              </Map>
            </div>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="状态"
            name="status"
            rules={[
              {
                required: true,
                message: '请选择场馆状态',
              },
            ]}
          >
            <Radio.Group>
              <Radio value="1">
                正常
              </Radio>
              <Radio value="2">
                暂停
              </Radio>
            </Radio.Group>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="排序"
            name="orderNum"
            rules={[
              {
                required: true,
                message: '请输入排序',
              },
            ]}
          >
            <InputNumber
              placeholder="请输入"
              min={0}
              max={100}
            />
          </FormItem>
          <FormItem
            {...submitFormLayout}
            style={{
              marginTop: 32,
            }}
          >
            <Button type="primary" onClick={onFinish} loading={submitting}>
              提交
            </Button>
            <Button
              style={{
                marginLeft: 8,
              }}
              onClick={() => window.history.back()}
            >
              返回
            </Button>
          </FormItem>
        </Form>
        <Modal
          title="提示"
          visible={visible}
          onOk={handleOk}
          onCancel={handleCancel}
          width={600}
        >
          <Row>
            <Col span={24}>
              <div style={{ height: 300 }} className="myAmap">
                <Map amapkey={Contanst.AMapKey} loading={Loading} zoom={15} center={tPosition} plugins={['ToolBar']}>
                  <Autocomplete options={pluginProps} onSelect={(e) => selectfunc(e)} modalPosition={tPosition} placeholder="请输入场馆地址" />
                  <Marker position={tPosition} draggable={true} events={markerEvents} />
                </Map>
              </div>
            </Col>
          </Row>
        </Modal>
      </Card>
    </PageHeaderWrapper>
  );
};

export default connect(({ loading }) => ({
  submitting: loading.effects['cubeShop/add'],
}))(BasicForm);
